package com.hcl.orm.core.executor.nativesql;

import com.hcl.orm.core.annotation.DBType;
import com.hcl.orm.core.exception.OrmException;
import com.hcl.orm.core.executor.DataSourceTypeLookup;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author hucl
 * @projectName jim-orm
 * @description: TODO
 * @date 2021/5/2816:15
 */
@Component
public class NativeSqlExecutorFactory implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Resource
    private DataSourceTypeLookup dataSourceTypeLookup;

    public <T extends NativeSqlExecutor> T getExecutor(Class<T> clazz, DBType dbType) {
        Map<String, T> beanMaps = this.applicationContext.getBeansOfType(clazz);

        return beanMaps.entrySet().stream().filter(i -> i.getValue().getTargetDB().contains(dbType))
                .findFirst().orElseThrow(() ->
                        new OrmException("can not find the sql executor.")
                ).getValue();
    }

    public <T extends NativeSqlExecutor> T getExecutor(Class<T> sqlExecutorClass) {
        return getExecutor(sqlExecutorClass,
                dataSourceTypeLookup.getDataSourceType(""));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
